import MENUS from '@/consts/menus';
import { ReducersPayloadAny } from '@/typings/redux.type';
import { createModel } from '@rematch/core';
import cookies from 'react-cookies';
import { TOKEN_COOKIE_NAME, CORGI_LOGIN_URL } from '../../consts/env';
import { RootModel } from '../rootModel';

export interface AppState {
  num: number;
  menuList: any[];
  imageToken: string;
  selectedKey: string;
}

export default createModel<RootModel>()({
  state: {
    num: 1,
    menuList: [], // 左侧菜单数据
    pageRole: {}, // 页面权限数据（字典）
    imageToken: '', // 七牛token
    selectedKey: '', // 当前激活菜单
  } as AppState,
  reducers: {
    updateState(state, payload: ReducersPayloadAny) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  effects: (dispatch) => ({
    async addNum(_, rootState) {
      dispatch.app.updateState({ num: rootState.app.num + 1 });
    },
    async deductNum(_, rootState) {
      dispatch.app.updateState({ num: rootState.app.num - 1 });
    },
    // 获取菜单权限列表
    async getMenusList() {
      dispatch.app.updateState({
        menuList: MENUS,
      });
      return [];
    },
    async logout() {
      // removeStorageAll();
      cookies.remove(`${TOKEN_COOKIE_NAME}`, { path: '/', domain: '.kaikeba.com' });
      document.location.href = CORGI_LOGIN_URL;
    },
    // 保存左侧菜单点击key，用于刷新页面时找到最后一次key
    async changeSelectedKey(key) {
      dispatch.app.updateState({ selectedKey: key });
    },
    // 获取页面权限相关信息
    async getPageRoleInfo() {
      return [];
    },
  }),
});
